package com.example.net.socket.client;


import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author zhaoyunlong
 * @date 2020/11/9
 * @description
 */
public class ClientSocket {


    public static void main(String[] args) {


        try (Socket client = new Socket("localhost", 8081);
             // 获取输出流，服务端发送数据
             OutputStream outputStream = client.getOutputStream()){
            // 创建socket对象，其实是开启实现io的虚拟接口（此接口不是java中接口, 类似与网线的插槽）
            //需要制定数据接收放的id地址和端口号

            String data = "hello, 您好----服务端！";
            outputStream.write(data.getBytes());
            outputStream.flush();

            // 截断输出流   告诉输出已经结束
            client.shutdownOutput();

            /**
             * 接收客户端的消息
             */
            InputStream inputStream =  client.getInputStream();
            byte[] readData = new byte[1024];
            int read;
            while ((read = inputStream.read(readData)) != -1) {
                System.out.println("从服务端接收的消息是："  + new String(readData, 0, read));
            }
            // 截断输出流   告诉输入已经结束
            client.shutdownInput();
            inputStream.close();
        }catch (Exception e) {
            e.printStackTrace();

        }
    }
}
